import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/admin/login.vue'
import Layout from '../layout/index.vue'
import NotFound from '@/views/error/NotFound.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/analytics'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/admin',
      name: 'admin',
      component: Layout,
      children: [
        {
          path: '/analytics',
          name: 'analytics',
          component: () => import('@/views/admin/analytics/index.vue'),
        },
        {
          path: '/workplace',
          name: 'workplace',
          component: () => import('@/views/admin/workplace/index.vue'),
        }
      ]
    },
    {
      path: '/system',
      name: 'system',
      component: Layout,
      children: [
        {
          path: '/account',
          name: 'account',
          component: () => import('@/views/system/account/index.vue'),
        },
        {
          path: '/columns',
          name: 'columns',
          component: () => import('@/views/system/columns/index.vue'),
        },
        {
          path: '/menu',
          name: 'menu',
          component: () => import('@/views/system/menu/index.vue'),
        },
        {
          path: '/role',
          name: 'role',
          component: () => import('@/views/system/role/index.vue'),
        },
        {
          path: '/department',
          name: 'department',
          component: () => import('@/views/system/department/index.vue'),
        }
      ]
    },
    {
      path: '/study',
      name: 'study',
      component: Layout,
      children: [
        {
          path: '/link',
          name: 'link',
          component: () => import('@/views/study/link/index.vue'),
        },
        {
          path: '/note',
          name: 'note',
          component: () => import('@/views/study/note/index.vue'),
        },
        {
          path: '/write',
          name: 'write',
          component: () => import('@/views/study/write/index.vue'),
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: '404',
      component: NotFound
    }
  ]
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  // 需要登录但未登录的页面
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }

  if(to.path == '/login' && isAuthenticated){
    router.replace('/')
  }
})

export default router
